package br.nextfm.dao;

import java.util.List;

import javax.persistence.Query;

import br.nextfm.model.Musica;

public class MusicaDao extends Dao {
	
	public boolean insert(Musica musica) {

		try {

			getManager().getTransaction().begin();
			getManager().persist(musica);
			getManager().getTransaction().commit();

			return true;

		} 

		catch (Exception e) {

			e.printStackTrace();

			return false;
		}
		
	}
	
	public boolean update(Musica musica) {
		
		try {

			getManager().getTransaction().begin();
			getManager().merge(musica);
			getManager().getTransaction().commit();

			return true;

		} 

		catch (Exception e) {

			e.printStackTrace();

			return false;
		}
		
	}
	
	public boolean delete(int id) {
		
		try {

			getManager().getTransaction().begin();
			Musica musica = getManager().find(Musica.class, id);
			getManager().remove(musica);
			getManager().getTransaction().commit();

			return true;

		} 

		catch (Exception e) {

			e.printStackTrace();

			return false;
		}
		
	}
	
	public Musica get(int id) {

		try {

			return getManager().find(Musica.class, id);

		} 

		catch (Exception e) {

			e.printStackTrace();

			return null;

		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Musica> getAll() {
		
		try {

			getManager().getTransaction().begin();
			Query query = getManager().createQuery("SELECT m FROM Musica m ORDER BY m.nome");

			return query.getResultList();

		}

		catch (Exception e) {

			e.printStackTrace();

			return null;

		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Musica> getAllBySearch(String nome) {
		
		try {

			getManager().getTransaction().begin();
			Query query = getManager().createQuery("SELECT m FROM Musica m  WHERE m.nome LIKE '%" + nome + "%' ORDER BY m.nome");

			return query.getResultList();

		}

		catch (Exception e) {

			e.printStackTrace();

			return null;

		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Musica> getTop() {
		
		try {

			getManager().getTransaction().begin();
			Query query = getManager().createQuery("SELECT m FROM Musica m ORDER BY m.id DESC");			
			
			return query.setMaxResults(5).getResultList();
			
		}

		catch (Exception e) {

			e.printStackTrace();

			return null;

		}
		
	}

}
